<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Exception;
use think\Request;
use think\Validate;

/**
 * 收货地址接口
 */
class Address extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    protected $model = null;

    public function __construct()
    {
        parent::__construct();
        $this->model = new \app\common\model\Address;
    }

    /**
     * 获取用户收货地址
     *
     */
    public function index()
    {
        $map = [
            'user_id' => $this->auth->id,
        ];

        $data = $this->model
            ->field('id,name,mobile,area,detail,is_default')
            ->where($map)
            ->select();

        $this->success('i18n:62',$data);
    }

    public function show(){
        //收货地址id
        $id = $this->request->request('id');

        $map = [
            'user_id' => $this->auth->id,
        ];
        //获取该收货地址
        $data = $this->model
            ->field('id,name,mobile,area,detail,is_default')
            ->where($map)
            ->find($id);

        if (!$data) {
            $this->error('i18n:132');
        }

        $this->success('i18n:62',$data);
    }

    /**
     * 添加收货地址
     * @return bool
     * @throws Exception
     */
    public function add(){
        $name = $this->request->request('name');
        $mobile = $this->request->request('mobile');
        $area = $this->request->request('area');
        $detail = $this->request->request('detail');
        $is_default = $this->request->request('is_default');

        //判断收货地址是否超出 默认最多10条
        $count = $this->model->where(['user_id' => $this->auth->id])->count();
        if ($count >= 10){
            $this->error('i18n:131');
        }

        $param = [
            'user_id'   => $this->auth->id,
            'name'      => $name,
            'mobile'    => $mobile,
            'area'      => $area,
            'detail'    => $detail,
            'is_default' => $is_default,
        ];

        //校验提交数据
        $this->checkData($param);

        Db::startTrans();
        try {
            //判断新增地址是否设置默认，更新原来的默认地址为0
            if ($is_default){
                $map = [
                    'user_id' => $this->auth->id,
                    'is_default' => 1,
                ];

                $data = [
                    'is_default' => 0,
                    'updatetime' => time(),
                ];
                $this->model->where($map)->update($data);
            }
            $result = $this->model->save($param);
            $address_id = $this->model->id;
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }


        $this->success('i18n:130',['address_id' => $address_id]);
    }

    public function edit(){
        //收货地址id
        $id = $this->request->request('id');
        $name = $this->request->request('name');
        $mobile = $this->request->request('mobile');
        $area = $this->request->request('area');
        $detail = $this->request->request('detail');
        $is_default = $this->request->request('is_default');

        $param = [
            'name'      => $name,
            'mobile'    => $mobile,
            'area'      => $area,
            'detail'    => $detail,
            'is_default' => $is_default,
            'updatetime' => time(),
        ];

        //校验提交数据
        $this->checkData($param);

        Db::startTrans();
        try {
            //判断更新地址是否设置默认，更新原来的默认地址为0
            if ($is_default) {
                $map = [
                    'user_id' => $this->auth->id,
                    'is_default' => 1,
                ];

                $data = [
                    'is_default' => 0,
                    'updatetime' => time(),
                ];
                $this->model->where($map)->update($data);
            }
            $this->model->where([
                'id'        => $id,
                'user_id'   => $this->auth->id,
            ])->update($param);
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('i18n:129',['address_id' => $id]);

    }

    protected function checkData($param){
        $rule = [
            'name'   => 'require|length:1,50',
            'mobile' => 'require', //|regex:^1\d{10}$
            'area'   => 'require|length:1,200',
            'detail' => 'require|length:1,200',
        ];

        $msg = [
            'name.require'      => 'i18n:128',
            'name.length'       => 'i18n:127',
            'mobile.require'    => 'i18n:126',
            'mobile.regex'      => 'i18n:125',
            'area.require'      => 'i18n:124',
            'area.length'       => 'i18n:123',
            'detail.require'    => 'i18n:122',
            'detail.length'     => 'i18n:121',
        ];

        //$this->validate($param,$rule,$msg);

        $validate = new Validate($rule, $msg);
        $result = $validate->check($param);
        if (!$result) {
            $this->error($validate->getError());
            return false;
        }

        return true;
    }

    public function setDefault(){
        $id = $this->request->request('id');

        Db::startTrans();
        try {
            //原先默认取消
            $map = [
                'user_id' => $this->auth->id,
                'is_default' => 1,
            ];
            $data = [
                'is_default' => 0,
                'updatetime' => time(),
            ];
            $this->model->where($map)->update($data);

            //当前设置默认
            $this->model->where([
                'id'        => $id,
                'user_id'   => $this->auth->id,
            ])->update(['is_default' => 1]);

            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $this->error('i18n:120');
        }

        $this->success('i18n:119',['address_id' => $id]);
    }

    public function del(){
        $id = $this->request->request('id');

        $map = [
            'id'        => $id,
            'user_id'   => $this->auth->id,
        ];

        $result = $this->model->where($map)->delete();
        if (!$result){
            $this->error('i18n:118');
        }

        $this->success('i18n:117',['address_id' => $id]);
    }
}
